package com.caigou.modules.personal.ui.page

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.viewmodel.FriendViewModel
import com.caigou.comm.base.viewmodel.RewardViewModel
import com.caigou.comm.base.widget.AddFriendDialog
import com.caigou.comm.base.widget.BuyFlowerDialog
import com.caigou.comm.base.widget.RewardDialog
import com.caigou.modules.personal.R
import com.caigou.modules.personal.adapter.PersonalPageAdapter
import com.caigou.modules.personal.bean.UserPageInfoBean
import com.caigou.modules.personal.databinding.ActivityPersonalPageBinding
import com.caigou.modules.personal.ui.page.fragment.*
import com.caigou.modules.personal.viewmodel.PersonalPageViewModel
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/09/30
 */
@Route(path = RouterPath.Personal.PAGE_PERSONAL_PAGE)
@AndroidEntryPoint
class PersonalPageActivity : BaseActivity() {

    private lateinit var binding: ActivityPersonalPageBinding
    private val personalPageViewModel: PersonalPageViewModel by viewModels()
    private val rewardViewModel: RewardViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()
    private val friendViewModel: FriendViewModel by viewModels()

    @Autowired(name = AppConstants.USER_ID)
    lateinit var userId: String

    private val itemNames = mutableListOf(
        "港彩",
        "澳彩",
        "港彩名人堂",
        "澳彩名人堂",
        "新加坡彩",
        "台彩",
        "猛料市场",
        "足球论坛",
        "民间资料"
    )

    private val fragments = mutableListOf<Fragment>(
        HkTicketFragment(),
        MacaoTicketFragment(),
        HkFamousFragment(),
        MacaoFamousFragment(),
        SingaporeTicketFragment(),
        TwTicketFragment(),
        MarketFragment(),
        SoccerFragment(),
        InfoFragment()
    )


    private val pagerAdapter: PersonalPageAdapter by lazy {
        PersonalPageAdapter(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPersonalPageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.personalPageLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.personalPageSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchUserPageInfo()
            }
        }

        pagerAdapter.setList(fragments)
        binding.personalPageViewPager2.adapter = pagerAdapter
        binding.personalPageViewPager2.isUserInputEnabled = false
        TabLayoutMediator(binding.personalPageTabLayout, binding.personalPageViewPager2, true, true) { tab, position ->
            tab.text = itemNames[position]
        }.attach()
        binding.personalPageViewPager2.offscreenPageLimit = itemNames.size

        binding.personalPageViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val view = fragments[position].view
                view?.let {
                    updatePagerHeightForChild(it, binding.personalPageViewPager2)
                }
            }
        })

        binding.personalPageIvShare.setOnClickListener {
            val bitmap = binding.personalPageLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        binding.personalPageTvBack.setOnClickListener {
            finish()
        }

        LiveDataBus.get().with(BusKey.LOAD_VP2_FINISH, Any::class.java).observe(this) {
            fragments[binding.personalPageViewPager2.currentItem].view?.apply {
                updatePagerHeightForChild(this, binding.personalPageViewPager2)
            }
        }

        fetchUserPageInfo()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(personalPageViewModel.userPageInfoLiveData, ::handleGetUserPageInfo)
        observe(followViewModel.followLiveData, ::handleSetFollow)
        observe(rewardViewModel.buyFlowerLiveData, ::handleBuyFlower)
        observe(rewardViewModel.rewardLiveData, ::handleSetReward)
        observe(friendViewModel.addFriendLiveData, ::handleAddFriend)
    }

    private fun handleGetUserPageInfo(result: Resource<UserPageInfoBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.personalPageSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取个人主页信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.personalPageSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }
                handlePageInfoUI(result.data!!)
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                fetchUserPageInfo()
            }
        }
    }

    private fun handleSetReward(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("打赏用户异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleBuyFlower(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("购买小红花异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleAddFriend(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("添加好友异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handlePageInfoUI(bean: UserPageInfoBean) {
        binding.personalPageLayoutHeader.apply {
            if (TextUtils.isEmpty(bean.headImg)) {
                headerIvAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@PersonalPageActivity, bean.headImg, headerIvAvatar)
            }
            headerTvNickname.text = bean.nickName
            headerIvLevel.setImageResource(levelAliasImage(bean.level))
            headerBtnScore.text = "高手积分${bean.score}>"
            headerTvSignature.text = if (TextUtils.isEmpty(bean.signature)) {
                "这个人很懒，他什么也没说..."
            } else {
                bean.signature
            }
            headerTvFollowNum.text = bean.followCount.toString()
            headerTvFansNum.text = bean.fansCount.toString()
            headerTvArticleNum.text = bean.posts.toString()
            headerTvPraiseNum.text = bean.winNicePoint.toString()

            headerTvInfo.visibility = if (AppBackgroundInfo.instance.hasLogin && userId == AppBackgroundInfo.instance.userBean!!.userId) {
                headerTvMessage.text = "我的留言"
                View.VISIBLE
            } else {
                headerTvMessage.text = "给TA留言"
                View.GONE
            }

            headerTvMessage.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_BOARD)
                        .withString(AppConstants.USER_ID, userId)
                        .navigation()
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            headerTvInfo.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_INFO)
                        .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Personal.TAG_INFO)
                        .navigation()
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }
        }

        binding.personalFooterLayout.apply {
            personalFooterLlContainer.visibility = if (AppBackgroundInfo.instance.hasLogin) {
                if (userId == AppBackgroundInfo.instance.userBean!!.userId) {
                    View.GONE
                } else {
                    View.VISIBLE
                }
            } else {
                View.VISIBLE
            }

            personalFooterBtnFollow.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, userId)
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            personalFooterLlReward.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    with(RewardDialog(this@PersonalPageActivity, bean.headImg, object : RewardDialog.IRewardClickCallback {
                        override fun onChargeMoney() {
                            showToast("暂未开放，敬请期待")
                        }

                        override fun onChargeFlower() {
                            val dialog = BuyFlowerDialog(this@PersonalPageActivity)
                            dialog.apply {
                                btnConfirm.setOnClickListener {
                                    rewardViewModel.buyFlower(AppBackgroundInfo.instance.userBean!!.userId, flowerNum)
                                    dismiss()
                                }
                                show()
                            }
                        }

                        override fun onReward(type: Int, num: Int) {
                            rewardViewModel.setReward(type, num, AppBackgroundInfo.instance.userBean!!.userId, bean.userId)
                        }

                    })) {
                        show()
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            personalFooterLlFriend.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    with(AddFriendDialog(this@PersonalPageActivity, bean.nickName)) {
                        btnConfirm.setOnClickListener {
                            val remark = etRemark.text.toString()
                            friendViewModel.addFriend(AppBackgroundInfo.instance.userBean!!.userId, bean.userId, remark)
                            dismiss()
                        }
                        show()
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            if (bean.concern) {
                personalFooterBtnFollow.setBackgroundResource(R.drawable.comm_btn_gray)
                personalFooterBtnFollow.setTextColor(Color.parseColor("#505050"))
                personalFooterBtnFollow.text = "已关注"
            } else {
                personalFooterBtnFollow.setBackgroundResource(R.drawable.comm_btn_orange)
                personalFooterBtnFollow.setTextColor(Color.parseColor("#FFFFFF"))
                personalFooterBtnFollow.text = "+关注"
            }
        }
    }


    private fun fetchUserPageInfo() {
        if (AppBackgroundInfo.instance.hasLogin) {
            personalPageViewModel.getUserPageInfo(userId, AppBackgroundInfo.instance.userBean!!.userId)
        } else {
            personalPageViewModel.getUserPageInfo(userId)
        }
    }

    private fun updatePagerHeightForChild(view: View, pager: ViewPager2) {
        view.post {
            val wMeasureSpec = View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
            val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(wMeasureSpec, hMeasureSpec)
            if (pager.layoutParams.height != view.measuredHeight) {
                pager.layoutParams = (pager.layoutParams).also { lp ->
                    lp.height = view.measuredHeight
                }
            }
        }
    }
}